<template>
  <div class="login-container">
    <el-card class="login-box">
      <template #header>
        <div class="login-header">
          <el-avatar :size="60" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
          <h2>宠物咖啡馆登录</h2>
        </div>
      </template>
      
      <el-form @submit.prevent="handleLogin" label-position="left" label-width="80px">
        <el-form-item label="角色">
          <el-select 
            v-model="selectedRole" 
            placeholder="请选择角色" 
            style="width: 100%"
            :disabled="isLoading"
          >
            <el-option 
              v-for="role in roles" 
              :key="role.value" 
              :label="role.label" 
              :value="role.value" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="用户名">
          <el-input 
            v-model="username" 
            placeholder="请输入用户名" 
            :prefix-icon="User"
            :disabled="isLoading"
          />
        </el-form-item>
        
        <el-form-item label="密码">
          <el-input 
            v-model="password" 
            type="password" 
            placeholder="请输入密码" 
            :prefix-icon="Lock"
            show-password
            :disabled="isLoading"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            native-type="submit" 
            style="width: 100%" 
            :loading="isLoading"
          >
            {{ isLoading ? '登录中...' : '登录' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { userApi } from '../services/api'
import { ElMessage, ElNotification } from 'element-plus'
import { User, Lock, Select } from '@element-plus/icons-vue'

const router = useRouter()
const username = ref('')
const password = ref('')
const selectedRole = ref('customer')
const isLoading = ref(false)

const roles = [
  { value: 'admin', label: '管理员' },
  { value: 'caretaker', label: '看护师' },
  { value: 'customer', label: '顾客' }
]

const handleLogin = async () => {
  if (!username.value || !password.value) {
    ElMessage.warning('请输入用户名和密码')
    return
  }

  isLoading.value = true

  try {
    // 调用登录API
    const response = await userApi.login(username.value, password.value)
    console.log('登录响应:', response)

    if (response.data.code === 200) {
      // 登录成功处理
      if (response.data && response.data.token) {
        localStorage.setItem('token', response.data.token)
      } else if (response.data && response.data.data && response.data.data.token) {
        // 兼容不同的返回格式
        localStorage.setItem('token', response.data.data.token)
      }

          // 登录成功提示
      ElNotification({
        title: '登录成功',
        message: '欢迎回来，' + username.value,
        type: 'success',
        duration: 2000
      })
      
      // 根据选择的角色跳转到不同页面
      const roleRoutes = {
        admin: '/admin',
        caretaker: '/caretaker',
        customer: '/customer'
      }
      
      // 使用await确保路由跳转完成
      await router.push(roleRoutes[selectedRole.value])
      console.log('路由跳转完成')
    }else{
      ElMessage.error('登录失败，请检查账号密码')
    }

  } catch (error) {
    // 登录失败
    console.error('登录失败:', error)
    
    // 显示错误信息
    if (error.response) {
      // 服务器返回了错误状态码
      ElMessage.error(error.response.data.message || '登录失败，请检查账号密码')
    } else if (error.request) {
      // 请求发出但没有收到响应
      ElMessage.error('无法连接到服务器，请检查网络连接')
    } else {
      // 请求配置出错
      ElMessage.error('请求错误: ' + error.message)
    }
    
    // 如果是开发环境，提供测试账号信息
    if (import.meta.env.DEV) {
      ElMessage.info('测试账号：admin，密码：123456')
    }
  } finally {
    isLoading.value = false
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  background: linear-gradient(135deg, #ffd3a5 0%, #fd6585 100%);
  overflow: hidden;
}

.login-box {
  width: 90%;
  max-width: 400px;
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.login-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 10px;
}

.login-header h2 {
  margin-top: 15px;
  font-weight: 600;
  color: #333;
}

:deep(.el-card__header) {
  padding-bottom: 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}
</style> 